package cn.wit.luohui.day10;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.junit.Test;

public class DemoFileOutputStream {
	@Test
	public void testStream() {
		File dir=new File("data/day10");
		
		dir.mkdir();//创建目录
		
		File file=new File(dir,"file.txt");
		//FileOutputStream fo=null;
		
//		try {
//			fo=new FileOutputStream(file,true);
//			//append往后面添加
//			fo.write('C');//int>char
//			fo.write("FFF".getBytes());
//		} catch (FileNotFoundException e1) {
//			
//			e1.printStackTrace();
//		} catch (IOException e) {
//			
//			e.printStackTrace();
//		}finally {//清理资源
//			if(fo!=null) {
//				try {
//					fo.close();
//				} catch (IOException e) {
//					
//					e.printStackTrace();
//				}
//			}
		//}
		
		try(FileOutputStream fo1=new FileOutputStream(file,true))//往后追加)
			
		{
			//append往后面添加
			fo1.write('C');//int>char
			fo1.write("FFF".getBytes());
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		//System.out.println(Arrays.toString("FFF".getBytes()));
		
	}
	//inputstream读文件
	@Test
	public void testInputStream() {
		File dir = new File("data/day10");
		File file = new File(dir, "file.txt");
		
		try (FileInputStream fi=new FileInputStream(file))
		{
			//read(),每次读取一个字符
			int c=fi.read();
			System.out.println((char)c);
			
			byte[] bytes=new byte[100];
			
			int count=fi.read(bytes);
			
//			while((count=fi.read(bytes))!=-1) {
//				System.out.println(new String(bytes, 0, count));
//				System.out.println("有几个字符：" + count);
//			}
			
			System.out.println("有几个字符：" + count);
			System.out.println(new String(bytes, 0, count));
		
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
	}
	@Test
	public void testChar() {
		System.out.println((int) 'A');
		System.out.println('A' - 'B');
		System.out.println((char) ('A' + 25));
	}
@Test
public void testFileCopy() throws IOException  {
	long start=System.currentTimeMillis();//获取当前时间（计时）
	
	File source = new File("E:\\camp2018\\视频\\day10\\04. 文件输入输出流.mp4");
	File target = new File("E:\\camp2018\\视频\\day10\\04.test.mp4");
	
	
	try (
			// 输入流，用来读文件
			FileInputStream fi=new FileInputStream(source);
			// 输出流， 用来写文件
			FileOutputStream fo = new FileOutputStream(target);
		)
	{
		byte[] contents = new byte[1024];
		
		while(true) {
			int count=fi.read(contents);
			if(count==-1) {
				break;
			}
			//读到多少位，就写多少位
			fo.write(contents, 0, count);
		}
		
	} catch (FileNotFoundException e) {
		
		e.printStackTrace();
	}
	long end=System.currentTimeMillis();
	System.out.println("耗时：" + (end - start));
}
}
